package com.handong.handserialprogram.module.devicetask;

import android.text.TextUtils;

import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.status.EmergencyMsg;
import com.handong.handserialprogram.model.status.EmergencyResponse;
import com.handong.handserialprogram.model.status.MissionOverResponse;
import com.handong.handserialprogram.model.status.RingResponse;
import com.handong.handserialprogram.module.base.BasePresenter;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.FootRingNewUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by userKey on 2017/12/2.
 */

public class DeviceTaskPresenter extends BasePresenter<DeviceTaskActivity> {

    private static final String TAG = DeviceTaskPresenter.class.getSimpleName();
    private SerialPortUtil mSerialPortUtil;
    private Vector<FootRingNewEntity> mRingList=new Vector<>();
    private CopyOnWriteArrayList<FootRingNewEntity> logoutFR;

    public DeviceTaskPresenter(BaseView view) {
        super(view);
        logoutFR=new CopyOnWriteArrayList<>();
    }

    protected void init() {
        EventBusUtil.register(this);
        mSerialPortUtil = SerialPortUtil.getInstance(mView);
    }

    /**
     * 接收脚环列表
     */
    @Subscribe(priority = 100, threadMode = ThreadMode.MAIN)
    public void receiveFootRingList(CopyOnWriteArrayList<FootRingNewEntity> list) {
        if (mSerialPortUtil == null || mView == null || !mView.isResume()) {
            return;
        }
       /* if (mRingList == null) {
            mRingList = list;
        }*/
        for (FootRingNewEntity entity:list) {
            if(entity.isMyBingding()&&!mRingList.contains(entity)){
                mRingList.add(entity);
            }
        }

        logoutFR.clear();
        for (FootRingNewEntity entity:mRingList) {
            if(entity.isMyBingding()&&entity.isNormalWork()){
                logoutFR.add(entity);
            }
        }


        mView.refreshDeviceList(mRingList);
    }

    /**
     * 开始上传数据
     */
    protected void beginUploadData(String missId) {
        SPUtil.putStringValue(SPUtil.MISSION_ID, missId);
        mSerialPortUtil.openUploadThread();
    }

    /**
     * 设备返回结果
     */
    @Subscribe(priority = 100, threadMode = ThreadMode.MAIN)
    public void receiveRingResponse(RingResponse response) {
        if (mView == null || !mView.isResume()) {
            return;
        }
        switch (response.getResponseCode()) {
            case RingResponse.LOGOUT_ORDER:
                if (response.isSuccess()) {
                    if(!logoutFR.isEmpty()){
                        logoutFR.remove(FootRingNewUtil.findFootRingById(logoutFR,response.getRingID()));
                        logoutAllFootRing();
                        if(logoutFR.isEmpty()){
                            mView.dismissLoadingDialog();
                            logoutSuccess();
                        }
                        break;
                    }else{
                        mView.dismissLoadingDialog();
                        logoutSuccess();
                    }
                } else {
                    mView.dismissLoadingDialog();
                    mView.logoutFootRingError(response.getRingID());
                }

                break;

            case RingResponse.SIM_ERROR:
                mView.simInitErrorMissOpen(response.getRingID());
                break;
            default:
                return;
        }
    }

    protected void logoutSuccess() {
        this.mSerialPortUtil.closeSerialPort();
        this.mSerialPortUtil = null;
        mView.finish();
    }

    /**
     *休眠脚环
     */
//    protected void logoutFootRing(String id) {
//        mView.showLoadDialog("正在休眠脚环 " + id + " ...");
//        mSerialPortUtil.logoutFootRing(id);
//    }

    /**
     *休眠全部脚环
     */
    public void logoutAllFootRing() {
        if(!logoutFR.isEmpty()&&mSerialPortUtil!=null){
            this.mView.showLoadDialog("正在休眠脚环...");
            this.mSerialPortUtil.mSendRunnable.DelayTime=100;
            this.mSerialPortUtil.mSendRunnable.isLoginOut=true;
        }
    }



    protected void requestStopMiss() {
        mView.showLoadDialog("正在请求结束任务...");
        mSerialPortUtil.finishMiss2Server();
    }



    /**
     * 服务器结束任务
     * @param response
     */
    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void receiveMissionOver(MissionOverResponse response) {
        if (mView != null) mView.dismissLoadingDialog();
        switch (response.getOrder()) {
            case MissionOverResponse.OVER_SUCCESS:// 服务器结束任务成功
                mSerialPortUtil.destroyFinishThread();
                mView.showResponseSuccessDialog();
                break;

            case MissionOverResponse.OVER_TIME_OUT://服务器任务结束连接超时
                mView.showFinMissTimeOutDialog();
                break;

            case MissionOverResponse.OVER_REJECT:// 服务器不允许结束任务
                mView.showServerRejectDialog();
                mSerialPortUtil.destroyFinishThread();
                break;

            case MissionOverResponse.OVER_ERROR://请求结束任务错误
                mView.showSendErrorDialog();
                break;

            case MissionOverResponse.OVER_RESPONSE://请求发出
                mView.showLoadDialog("请求已发送，等待指挥中心回复...");
                break;

            case MissionOverResponse.SERVER_REQUEST:// 服务器请求结束任务
                mView.showMissionOverDialog();
                break;
        }
    }

    protected void stopUploadData() {
        mSerialPortUtil.closeUploadData();
        mView.missionIsFinished();
        for (FootRingNewEntity entity:mRingList) {
            mSerialPortUtil.logoutFootRing(entity.getRingID());
        }

    }




    protected void queryMissionState() {
        if (!AsyncHttpUtil.isNetworkConnected(mView)) {
            return;
        }
        String missId = SPUtil.getStringValue(SPUtil.MISSION_ID);
        RequestParams params = new RequestParams("visit", "GetState");
        params.put("MissId", missId);
        mView.showLoadDialog("正在查询任务状态...");
        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                mView.dismissLoadingDialog();
                AppUtil.showShortToast(mView, "服务器无响应");
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, "查询任务状态: " + s);
                if (TextUtils.isEmpty(s)) {
                    return;
                }
                try {
                    JSONObject object = new JSONObject(s);
                    if (!object.getBoolean("isClose")) {
                        stopUploadData();
                    } else {
                        requestStopMiss();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mView.dismissLoadingDialog();
                    AppUtil.showShortToast(mView, "服务器无响应");
                }
            }
        });
    }



    /**
     * 报警反馈
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveEmergencyResult(EmergencyResponse response) {
        if (mView == null || !mView.isResume()) {
            return;
        }
        mView.dealEmergencyResponse(response);
    }
    /**
     * 报警反馈
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveEmergencyMsg(EmergencyMsg msg) {
        if (mView == null || !mView.isResume()) {
            return;
        }
        if (msg.isStart()) {
            mView.sendEmergencyRequest();
        } else {
            mView.askUserForEmergency();
        }
    }

    /**
     * 结束任务后才能退出
     * @return
     */
    protected boolean isStopExit() {
        if (mView != null && mView.isMissionExecuting()) {
            AppUtil.showShortToast(mView, "结束任务后，才能退出");
            return true;
        }
        if (mRingList != null && !mRingList.isEmpty()) {

            for ( FootRingNewEntity entity :mRingList) {
                if (entity.isNormalWork()) {
                    mView.showExitDialog();
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    protected void exit() {
        EventBusUtil.unRegister(this);
        super.exit();
    }
}
